#include "NezhaCWriteFile.h"
#include "NezhaCFileSystem.h"

using namespace Nezha;
using namespace stream;


CWriteFile::CWriteFile(const char* fileName, bool append)
: mFileSize(0)
{
	mFilename = fileName;
	openFile(append);
}

CWriteFile::~CWriteFile()
{
}

//! returns if file is open
bool CWriteFile::isOpen() const
{
	return mFilePtr != 0;
}

//! returns how much was read
int CWriteFile::write(const void* buffer, u32 sizeToWrite)
{
	if (!isOpen())
		return 0;

	return fwrite(buffer, 1, sizeToWrite, mFilePtr->mFile);
}

void CWriteFile::flush()
{
	if (!isOpen())
		return;

	fflush(mFilePtr->mFile);
}

bool CWriteFile::seek(long finalPos, bool relativeMovement)
{
	if (!isOpen())
		return false;

	return fseek(mFilePtr->mFile, finalPos, relativeMovement ? SEEK_CUR : SEEK_SET) == 0;
}

//! returns where in the file we are.
long CWriteFile::getPos() const
{
	return ftell(mFilePtr->mFile);
}

//! opens the file
void CWriteFile::openFile(bool append)
{
	if (mFilename.size() == 0)
	{
		mFilePtr = 0;
		return; 
	}

	mFilePtr = CFileSystem::open(mFilename.c_str(), append ? "ab" : "wb");

	if (mFilePtr)
	{
		// get FileSize

		fseek(mFilePtr->mFile, 0, SEEK_END);
		mFileSize = ftell(mFilePtr->mFile);
		fseek(mFilePtr->mFile, 0, SEEK_SET);
	}
}

//! returns name of file
const char* CWriteFile::getFileName() const
{
	return mFilename.c_str();
}

//! return full path
const char* CWriteFile::getFullPath() const
{
	return mFilePtr->mFullPath.c_str();
}

IWriteFile* 
	InternalCreateWriteFile(const char* fileName, bool append)
{
	CWriteFile* file = NZ_New CWriteFile(fileName, append);
	if (file->isOpen())
		return file;

	//file->drop();
	return 0;
}